package com.sample.security;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletConfig;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.access.BeanFactoryLocator;
import org.springframework.beans.factory.access.BeanFactoryReference;
import org.springframework.context.access.ContextSingletonBeanFactoryLocator;

import com.sample.model.Role;
import com.sample.model.User;
import com.sample.service.UserService;

import flex.messaging.security.LoginCommand;

public class SampleLoginCommand implements LoginCommand {
	
	private BeanFactory beanFactory;
	private UserService userService;
	
	private static Log log = LogFactory.getLog(SampleLoginCommand.class);

	public Principal doAuthentication(String loginId, Object credentials) {
		log.debug("doAuthentication");
		setupBeans();
		
		User user = userService.fetchByLoginAndPassword(loginId, (String)credentials);
		if(user != null){
			List<String> roles = new ArrayList<String>(5);
			for(Role role : user.getRoles()){
				roles.add(role.getName());
			}
			return new SamplePrincipal(loginId, roles);
		}

		return null;
	}

	private void setupBeans() {
		if(beanFactory == null){
			BeanFactoryLocator bfl = ContextSingletonBeanFactoryLocator.getInstance("classpath:beanRefContext.xml");
			BeanFactoryReference bfRef = bfl.useBeanFactory("application.context");
			beanFactory = bfRef.getFactory();
		}
		if(userService == null){
			userService = (UserService) beanFactory.getBean("userService");
		}
	}

	//roles should be a list of Strings, unfortunately we can't type it because it's from the implementing class
	@SuppressWarnings("unchecked")
	public boolean doAuthorization(Principal principal, List roles) {
		log.debug("doAuthorization");
		SamplePrincipal e2ePrincipal = (SamplePrincipal)principal;
		return e2ePrincipal.getRoles().containsAll(roles);

	}

	public boolean logout(Principal principal) {
		log.debug("logout");
		//Don't need to do anything on logout
		return true;
	}

	public void start(ServletConfig config) {
		//Don't need to do anything on start
	}

	public void stop() {
		//Don't need to do anything on stop
	}

}
